// A simple program which interfaces to the W-Prolog engine.
// Author: Michael Winikoff (winikoff@cs.mu.oz.au)
// Date: 6/3/97
//
// Usage: java Go append.pl "append([1,2],X,[1,2,3,4])"
// 
// 
package test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;

import ai.wprolog.essentials.Engine;
import ai.wprolog.essentials.ParseString;
import ai.wprolog.essentials.Term;
import ai.wprolog.essentials.TermList;

import util.essential.SourceGetter;

public class Go2 {
	static public void main(String args[]) {
		String program, queryFileName = "test/append.qry", programFileName = "test/append.pl";
		Vector<String> queries;
		try {
			program = Go2.vectorToString(Go2.getSourceFromAFile(programFileName));
			System.out.println("=====================Program:");
			System.out.println(program);
			System.out.println("=====================");
			queries = Go2.getSourceFromAFile(queryFileName);
			// Have loaded program ... run query ...
			for (Iterator<String> iterator = queries.iterator(); iterator
					.hasNext();) {
				String query = iterator.next();
				System.out.println("=====================Queries:");
				System.out.println("Q: "+query);
				System.out.println("A: -------------------------");
				Go2.run(program, query);
				System.out.println("=====================");
			}
		} catch (FileNotFoundException x) {
			System.out.println("Can't open: " + args[0]);
		} catch (java.io.IOException x) {
			System.out.println("Can't read: " + args[0]);
		}
	}

	static private Vector<String> getSourceFromAFile(String fileName)
			throws IOException {
		Vector<String>tmp = SourceGetter.config.getSource(fileName);
		System.out.println(tmp.size());
		return tmp;
	}

	static private String vectorToString(Vector<String> lines) {
		StringBuffer buff = new StringBuffer();
		final String LN = "\n";
		for (Iterator<String> iterator = lines.iterator(); iterator.hasNext();) {
			String string = iterator.next();
			buff.append(string + LN);
		}
		return new String(buff.toString());
	}

	static private void run(String prog, String query) {
		Term t;
		Engine eng;
		final String NEGATIVE_ANSWER = "No.";
		try {
			// second argument null ... nowhere for error to be indicated
			t = new Term(new ParseString(query, null));
			try {
				eng = new Engine(t, ParseString.consult(prog, new Hashtable<String,TermList>(),
						null));
				// don't indicate error
				System.out.println(">>> Ans: "+eng.run());
				String ans;
				do{
					ans = eng.more();
					if(!ans.endsWith(NEGATIVE_ANSWER)){
						System.out.println(">>> Ans: "+ans);
					}
				}while(!ans.endsWith(NEGATIVE_ANSWER));
			} catch (Exception f) {
				System.out.println("Can't parse program!");
			}
		} catch (Exception f) {
			System.out.println("Can't parse query!\n");
			t = null; // dummy
		}
	}
}
